package com.cloudfun.msglisten.service;


import cn.hutool.http.HttpUtil;
import com.cloudfun.msglisten.common.model.dto.dingtalk.Content;
import com.cloudfun.msglisten.common.model.dto.dingtalk.RobotMessageAtDTO;
import com.cloudfun.msglisten.common.model.dto.dingtalk.RobotMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Huqin on 2020/5/13
 */
@Slf4j
@Service
public class DingTalkService {

    @Value("${aliyun.dingtalk.robot.webhook}")
    private String dingUrl;

    @Value("${dingtalk.robot.enable}")
    private Boolean robotEnable;

    ExecutorService dingTalkSendExecutor = new ThreadPoolExecutor(2, 2, 20,TimeUnit.SECONDS, new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.DiscardOldestPolicy());

    public void sendMessage(Content content, RobotMessageAtDTO at) {
        RobotMessageDTO robotMessageDTO = new RobotMessageDTO(content, at);
        //推送消息（http请求）
        String result = HttpUtil.post(dingUrl, robotMessageDTO.toJson());
        log.info("钉钉机器人通知结果：{}", result);
    }

    public void sendMessage(Content content) {
        RobotMessageDTO robotMessageDTO = new RobotMessageDTO(content);
        doSend(robotMessageDTO);
    }

    private void doSend(RobotMessageDTO robotMessageDTO) {
        // 线上才发送
        if (BooleanUtils.isTrue(robotEnable)) {
            //推送消息（http请求）
            dingTalkSendExecutor.execute(() -> {
                String result = HttpUtil.post(dingUrl, robotMessageDTO.toJson());
                log.info("钉钉机器人通知结果：{}", result);
            });

        }
    }

}
